package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 登陆控制
// 适配器模式
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    // 登陆检查即可
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfo user = null;
        if(handler instanceof HandlerMethod){
            // 动态请求过滤
            // 1.判断请求方法上面是否贴有@RequireLogin标签
            HandlerMethod hm = (HandlerMethod) handler;
            if(hm.hasMethodAnnotation(RequireLogin.class)){
                // 2.如果有, 进行登陆检查
                String token = CookieUtil.getToken(request, response);
                user = userInfoRedisService.getUserByToken(token);
                if(user == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        // 如果没有,直接放行
        request.getSession().setAttribute("userInfo", user);
        return true;
    }
}
